package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2022-07-03
 * Time: 22:21
 */
public class UserDao {
//    封装针对用户表的基本操作（增删改查）
    //主要实现
    //（1）根据用户名来查找用户信息
    public User selectByName(String username){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql="select * from user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setString(1,username);
            resultSet=statement.executeQuery();//指向查询操作，结果放到resultSet里面
            if(resultSet.next()){//username使用unique约束，只能查到1个或0个，用if判断即可，不用while了
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUserName(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close((com.mysql.jdbc.Connection)connection,statement,null);
        }
        return null;
    }
    //（2）根据用户id查找用户信息
    public User selectById(int userId){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql="select * from user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet=statement.executeQuery();//指向查询操作，结果放到resultSet里面
            if(resultSet.next()){//username使用unique约束，只能查到1个或0个，用if判断即可，不用while了
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUserName(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close((com.mysql.jdbc.Connection)connection,statement,null);
        }
        return null;
    }


}
